//
//  RefreshControl.swift
//  SinaWeibo
//
//  Created by Tony-ztb on 15/12/23.
//  Copyright © 2015年 Tony-ztb. All rights reserved.
//

import UIKit
import SnapKit

enum RefreshStatusEnum: Int {
    // 默认状态, 下拉起飞
    case Normal = 0
    // 用户下拉还没松手的时候的状态, 放开起飞
    case Pulling = 1
    // 用户松开手后的状态, 正在加载
    case Refreshing = 2
}

// 自定义刷新控件的高度
private let RefreshViewHeight: CGFloat = 60

class RefreshControl: UIControl {
    
    // 定义属性, 保存上一次的刷新状态
    var oldRefreshStatus: RefreshStatusEnum = .Normal
    
    // MARK: 定义外部模型属性
    var refreshStatus: RefreshStatusEnum = .Normal {
        didSet {
            switch refreshStatus {
            case .Pulling:
//                print("准备起飞")
                // 提示
                tipLabel.text = "准备起飞"
                // 箭头旋转
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI * (-0.999)))
                })
            case .Refreshing:
//                print("正在加载")
                // 提示
                tipLabel.text = "加载中..."
                // 隐藏箭头
                arrowIcon.hidden = true
                // 小菊花转动
                loadIcon.startAnimating()
                // 修改contentInset
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var inset = self.scrollView!.contentInset
                        inset.top += RefreshViewHeight
                        self.scrollView?.contentInset = inset
                })
                // 主动触发control的响应事件方法  刷新 数据
                sendActionsForControlEvents(.ValueChanged)
            case .Normal:
//                print("下拉起飞")
                
                if oldRefreshStatus == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var inset = self.scrollView!.contentInset
                        inset.top -= RefreshViewHeight
                        self.scrollView?.contentInset = inset
                    })
                }
                
                // 显示箭头
                arrowIcon.hidden = false
                // 小菊花停止转动
                loadIcon.stopAnimating()
                // 提示
                tipLabel.text = "下拉起飞"
                // 设置箭头方向
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity
                })
            }
            // 保存上一次的刷新状态
            oldRefreshStatus = refreshStatus
        }
    }
    
    // 定义属性, 记录父视图
    var scrollView: UIScrollView?
    
    // view的生命周期方法
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        // 可以获取当前控件的父视图
        // 观察添加当前视图的contentOffSet
        if let myFather = newSuperview as? UIScrollView {
            // 如果父视图能转成UIScrollView
            self.scrollView = myFather
            // kvo
            self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
    }
    
    // 实现kvo方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
//        print(change)
//        print(scrollView?.contentOffset)
        
        // 获取tableView的临界值
        let insetTop = scrollView?.contentInset.top ?? 0
        let conditionValue = -(RefreshViewHeight + insetTop)
        // 获取tableView的偏移量contentOffset
        let offsetY = scrollView?.contentOffset.y ?? 0
        
//        print(conditionValue)
//        print(offsetY)
        if scrollView!.dragging {
            // 在拖拽的状态下
            if refreshStatus == .Normal && offsetY < conditionValue {
                // 开始准备起飞状态
                refreshStatus = .Pulling
            } else if refreshStatus == .Pulling && offsetY > conditionValue {
                // 开始下拉起飞状态
                refreshStatus = .Normal
            }
        } else {
            // 不在拖拽的状态下
            if refreshStatus == .Pulling {
                refreshStatus = .Refreshing
            }
        }
    }
    
    // 自定义 模拟系统菊花停止转动
    func endRefreshing() {
        let delta = dispatch_time(DISPATCH_TIME_NOW, Int64(1) * Int64(NSEC_PER_SEC))
        
        dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
            
            self.refreshStatus = .Normal
        }
    }
    
    // 移除kvo
    deinit {
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
    // 设置frame
    override init(frame: CGRect) {
        
        let rect = CGRect(x: 0, y: -RefreshViewHeight, width: screenW, height: RefreshViewHeight)
        super.init(frame: rect)
        // 设置背景图片
        backgroundColor = UIColor(patternImage: UIImage(named: "new_feature_3")!)

        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: 设置页面和布局
    private func setupUI() {
        // 添加子视图
        addSubview(loadIcon)
        addSubview(arrowIcon)
        addSubview(tipLabel)
        
        // 设置自动约束
        
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(15)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(tipLabel.snp_left).offset(-5)
            make.centerY.equalTo(tipLabel.snp_centerY)
        }
        
        loadIcon.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon)
        }
        
    }
    
    // MARK: 懒加载所有子视图
    // 箭头
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    // 起飞
    private lazy var tipLabel: UILabel = UILabel(title: "下拉起飞", color: UIColor.grayColor(), fontSize: 14)
    // 菊花
    private lazy var loadIcon: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
}
